package com.ruoyi.system.task;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.system.domain.BaseLiveTournament;
import com.ruoyi.system.mapper.BaseLiveTournamentMapper;
import com.ruoyi.system.service.impl.BaseLiveTournamentServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Wangbj
 * @date 2024年05月10日 17:05
 */
@Slf4j
@Component
public class LiveTaskJob {

    @Resource
    private BaseLiveTournamentServiceImpl baseLiveTournamentService;

    @Resource
    BaseLiveTournamentMapper baseLiveTournamentMapper;

    /**
     * 程序启动时关闭所有直播间
     */
    @PostConstruct
    public void init() {
        log.info("程序启动 开始检查是否存在直播异常数据。。。。。");
        extracted();
        log.info("检查结束。。。。。");

    }


    /**
     * 程序关闭时 关闭所有直播间
     */
    @PreDestroy
    public void onShutdown() {
        log.info("程序关闭 开始检查是否存在直播异常数据。。。。。");
        extracted();
        log.info("检查结束。。。。。");
    }

    private void extracted() {
        //拿到所有未关闭的任务
        LambdaQueryWrapper<BaseLiveTournament> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(BaseLiveTournament::getState,2);//只要不是已关播都拿出来
        List<BaseLiveTournament> baseLiveTournaments = baseLiveTournamentMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(baseLiveTournaments)){
            log.info("不存在未关闭的异常直播数据。。");
            return;
        }
        log.info("未关闭的直播数据共【{}】条，id【{}】",baseLiveTournaments.size(),baseLiveTournaments.stream().map(BaseLiveTournament::getId).collect(Collectors.toList()));
        baseLiveTournaments.forEach( item ->{
            try {
                baseLiveTournamentService.endLive(item.getRoomNumber());
            }catch (Exception e){
                //异常可能是因为直播已经关了
                LambdaUpdateWrapper<BaseLiveTournament> updateWrapper =new LambdaUpdateWrapper<>();
                updateWrapper.eq(BaseLiveTournament::getId,item.getId());
                updateWrapper.set(BaseLiveTournament::getState,2);
                baseLiveTournamentMapper.update(null,updateWrapper);
            }
        });
    }

}
